<?php

		namespace Administrator\Controller;
		use Administrator\Utility\UserPassword;
		use Zend\Session\Container;
		use Zend\View\Model\ViewModel;
		use Zend\Mvc\Controller\AbstractActionController;
		use Zend\Mvc\MvcEvent;
		use Administrator\Form\LoginForm;
		use Administrator\Form\Filter\LoginFilter;
		use Administrator\Model\User;
		use Administrator\Model\ListUser;
		use Administrator\Model\Resource;

		class LoginController extends HeadController {
			
			protected $storage;
			protected $authservice;
			protected $authserviceactive;
			protected $UserTable;
			protected $ResourcesTable;
			
			public function indexAction(){
				$this->layout('layout/login');											
				$request = $this->getRequest();				
				$view = new ViewModel();								
				$loginForm = new LoginForm();
				$loginForm->loginform('loginForm');
				$loginfilter = new LoginFilter();
				$loginfilter->loginformfilter();
				$loginForm->setInputFilter($loginfilter );
				if($request->isPost()){
					$data = $request->getPost();
					$loginForm->setData($data);
					if($loginForm->isValid()){ 
						
						$data = $loginForm->getData();        
						$userPassword = new UserPassword();
						
						$encyptPass = $userPassword->create($data['password']);
						
						$this->getAuthService()
						->getAdapter()
						->setIdentity($data['email'])
						->setCredential($encyptPass);
											
						$this->getAuthServiceActive()
						->getAdapter()
						->setIdentity($data['email'])
						->setCredential($encyptPass);
						
						$result = $this->getAuthService()->authenticate();
						$activeUser = $this->getAuthServiceActive()->authenticate();
						if ($result->isValid() && $activeUser->isValid()) {
							
							$userDetails = $this->_getUserDetails(array(
									'EMAIL_USER' => $data['email']
							), array(
									'ID_USER'
							));

							$session = new Container('User');
							$session->offsetSet('email', $data['email']);
							
							$session->offsetSet('userId', $userDetails[0]['user_id']);
							$session->offsetSet('roleId', $userDetails[0]['role_id']);
							$session->offsetSet('roleName', $userDetails[0]['role_name']);
							
							$this->flashMessenger()->addMessage(array('success' => 'Xin chào.'));
							return $this->redirect()->toRoute('product');
							// Redirect to page after successful login
						}else if($result->isValid() && !$activeUser->isValid())
							$this->flashMessenger()->addMessage(array('error' => 'Tài khoản của bạn chưa được kích hoạt!.'));
						else{
							$this->flashMessenger()->addMessage(array('error' => 'Mật khẩu hoặc Email đăng nhập sai!.'));
							// Redirect to page after login failure
						}
						return $this->redirect()->toRoute('system');
						// Logic for login authentication                
					}else{
						$errors = $loginForm->getMessages();
						//prx($errors);  
					}
				}        
				
				$view->setVariable('loginForm', $loginForm);
				return $view;
			}
			
			private function getAuthService()
			{
				if (! $this->authservice) {
					$this->authservice = $this->getServiceLocator()->get('AuthService');
				}
				return $this->authservice;
			}

			private function getAuthServiceActive()
			{
				if (! $this->authserviceactive) {
					$this->authserviceactive = $this->getServiceLocator()->get('AuthServiceActive');
				}
				return $this->authserviceactive;
			}
			
			public function logoutAction(){
				$session = new Container('User');
				$session->getManager()->destroy();
				$this->getAuthService()->clearIdentity();
				return $this->redirect()->toRoute('system');
			}

			private function _getUserDetails($where, $columns)
			{
				$userTable = $this->getServiceLocator()->get("UserTable");
				$users = $userTable->getUsers($where, $columns);
				return $users;
			}

			public function listuserAction(){
				$this -> headsAction();
				$this->layout('layout/backend');
				$ListUserTable = $this->getServiceLocator()->get("UserTable");
				$viewModel  = new ViewModel(array(
						'listuser' => $ListUserTable->listUser(),
						'countUser' => $this->getUserTable()->countUser()
				));
				return $viewModel;
			}
			
			public function resourceAction(){
				$this -> headsAction();
				$this->layout('layout/backend');
				$ResourceTable = $this->getServiceLocator()->get("ResourceTable");
				$viewModel  = new ViewModel(array(
						'ResourceTable' => $ResourceTable->getAllResources(),
						'countgetAllResources' => $this->getResourcesTable()->countResources()
				));
				return $viewModel;
			}
			
			public function addAction(){
				$this -> headsAction();
				$this->layout('layout/backend');
				$request = $this->getRequest();
				$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');			
				$form = new LoginForm();
				$form->userform(null,$dbAdapter);
				
				$filterform = new LoginFilter();
				$filterform->userformfilter($dbAdapter);
				$form->setInputFilter($filterform);
				
				if($request->isPost()){
					$data = $request->getPost();
					$form->setData($data);
					$user = new ListUser();
					if($form->isValid()){
						$user->addArray($data);
						$this->getUserTable()->saveUser($user,0);
						// Redirect to list of product
						return $this->redirect()->toRoute('system/listuser');
					}
				}
				 
				//Truyền đối tượng UserForm vào đối tượng ProductForm
				$viewModel  = new ViewModel(array(
						'UserForm' => $form,
				));
				//Đưa đối tượng ViewModel ra ngoài VIEW
				return $viewModel;
			}
			
			public function addresourceAction(){
				$this -> headsAction();
				$this->layout('layout/backend');
				$request = $this->getRequest();
				$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
				$form = new LoginForm();
				$form->addresourceform(null,$dbAdapter);
			
				if($request->isPost()){
					$data = $request->getPost();
					$form->setData($data);
					$Resource = new Resource();
					if($form->isValid()){
						$Resource->addArray($data);
						$this->getResourcesTable()->saveResource($Resource,0);
						// Redirect to list of product
						return $this->redirect()->toRoute('system/resource');
					}
				}
					
				//Truyền đối tượng UserForm vào đối tượng ProductForm
				$viewModel  = new ViewModel(array(
						'resourceForm' => $form,
				));
				//Đưa đối tượng ViewModel ra ngoài VIEW
				return $viewModel;
			}
			
			public function activeAction(){
				$id = (int) $this->params()->fromRoute('id', 0);
				$idquery = (int) $this->params()->fromQuery('actives');
				$this->getUserTable()->updateActive($id,$idquery);
				$this->redirect()->toUrl($this->getRequest()->getServer('HTTP_REFERER'));
			}
			
			public function deleteAction()
			{
				$id = $this->params()->fromRoute('id');
				$this->getUserTable()->deleteUser($id);
				return $this->redirect()->toRoute('system/listuser');
				 
			}
						
			public function editAction(){
				$this->layout('layout/backend');
				 
				$id = (int) $this->params()->fromRoute('id', 0);
				 
				if (!$id) {
					return $this->redirect()->toRoute('system', array(
							'action' => 'add'
					));
				}else{
					//get url hien tai var_dump($this->request->getRequestUri());die;
					$user = $this->getUserTable ()->getUser ( $id );
					if(empty($user)){
						return $this->notFoundAction ();
					}else{
						
						$this -> headsAction($user->NAME);
						$urlhientai = $this->request->getRequestUri();
						$url = '/system/edit/'.$id.'-'.$this->vn2latin($user->NAME).'.html';
						if($urlhientai != $url)
							$this->redirect()->toUrl($url);
						$request = $this->getRequest();
						$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
						$form = new LoginForm();
						$form->userform(null,$dbAdapter);						
						$filterform = new LoginFilter();
						$filterform->userformfilter($dbAdapter);
						$form->setInputFilter($filterform);
						$form->bind ( $user );
						
						//Truyền đối tượng UserForm vào đối tượng ProductForm
						$viewModel  = new ViewModel(array(
								'useredit' => $form,
						));
						
						if($request->isPost()){
							$data = $request->getPost();
							$form->setData($data);
							$usert = new ListUser();
							if($form->isValid()){
								$usert->addArray($data);
								$this->getUserTable()->saveUser($usert,$id);
								// Redirect to list of product
								return $this->redirect()->toRoute('system/listuser');
								 
							}
						};
			
						//Đưa đối tượng ViewModel ra ngoài VIEW
						return $viewModel;
						
					}
				}
			}
			
			public function editresourceAction(){
				$this->layout('layout/backend');
					
				$id = (int) $this->params()->fromRoute('id', 0);
					
				if (!$id) {
					return $this->redirect()->toRoute('system', array(
							'action' => 'addresource'
					));
				}else{
					//get url hien tai var_dump($this->request->getRequestUri());die;
					$Resource = $this->getResourcesTable ()->getResource ( $id );
					if(empty($Resource)){
						return $this->notFoundAction ();
					}else{
			
						$this -> headsAction($Resource->name_resource);
						$request = $this->getRequest();
						$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
						$form = new LoginForm();
						$form->addresourceform(null,$dbAdapter);
						$form->bind ( $Resource );
			
						//Truyền đối tượng UserForm vào đối tượng ProductForm
						$viewModel  = new ViewModel(array(
								'Resourceedit' => $form,
						));
			
						if($request->isPost()){
							$data = $request->getPost();
							$form->setData($data);
							$Resource = new Resource();
							if($form->isValid()){
								$Resource->addArray($data);
								$this->getResourcesTable()->saveResource($Resource,$id);
								// Redirect to list of product
								return $this->redirect()->toRoute('system/resource');
									
							}
						};
							
						//Đưa đối tượng ViewModel ra ngoài VIEW
						return $viewModel;
			
					}
				}
			}

			public function minifyfileAction(){
				$this->layout('layout/backend');
				$this -> headsAction();
				$request = $this->getRequest();
				$form = new LoginForm();
				$form->minifyform();
				//$filterminify = new LoginFilter();
				//$filterminify->minifyfilter();
				//$form->setInputFilter($filterminify);
				$alert = null;
			   if($request->isPost()){
					$data = $request->getPost();
					$form->setData($data);
					$minify = new ListUser();
					$minify->jsandcssfile($data);					
					if($form->isValid()){
								//var_dump($minify->jsandcssfile);die;	
						$arr = array();
						foreach ($minify->jsandcssfile as $key=>$val){
							$path_parts = pathinfo($val);
							$arr[$val] = $path_parts['dirname'].'/'.$path_parts['filename'].'.min.'.$path_parts['extension'];
							if($path_parts['extension'] == 'js')
								$alert = $this->minifyJS($arr);
							else 
								$alert = $this->minifyCSS($arr);
							
						};
                    						
					}
				}
				
				//Truyền đối tượng UserForm vào đối tượng ProductForm
				$viewModel  = new ViewModel(array(
						'minifyform' => $form,
						'alert' => $alert,
				));
				//Đưa đối tượng ViewModel ra ngoài VIEW
				return $viewModel;
			}
			
			public function deleteResourceAction()
			{
				$id = $this->params()->fromRoute('id');
				$this->getResourcesTable()->deleteResource($id);
				return $this->redirect()->toRoute('system/resource');
					
			}
			
			public function getUserTable()
			{
				if (!$this->UserTable) {
					$sm = $this->getServiceLocator();
					$this->UserTable = $sm->get('Administrator\Model\UserTable');
				}
				return $this->UserTable;
			}
			
			public function getResourcesTable()
			{
				if (!$this->ResourcesTable) {
					$sm = $this->getServiceLocator();
					$this->ResourcesTable = $sm->get('Administrator\Model\Resources');
				}
				return $this->ResourcesTable;
			}
			
			function vn2latin($cs, $tolower = false)
			{
				/*Mảng chứa tất cả ký tự có dấu trong Tiếng Việt*/
				$marTViet=array("à","á","ạ","ả","ã","â","ầ","ấ","ậ","ẩ","ẫ","ă",
						"ằ","ắ","ặ","ẳ","ẵ","è","é","ẹ","ẻ","ẽ","ê","ề",
						"ế","ệ","ể","ễ",
						"ì","í","ị","ỉ","ĩ",
						"ò","ó","ọ","ỏ","õ","ô","ồ","ố","ộ","ổ","ỗ","ơ",
						"ờ","ớ","ợ","ở","ỡ",
						"ù","ú","ụ","ủ","ũ","ư","ừ","ứ","ự","ử","ữ",
						"ỳ","ý","ỵ","ỷ","ỹ",
						"đ",
						"À","Á","Ạ","Ả","Ã","Â","Ầ","Ấ","Ậ","Ẩ","Ẫ","Ă",
						"Ằ","Ắ","Ặ","Ẳ","Ẵ",
						"È","É","Ẹ","Ẻ","Ẽ","Ê","Ề","Ế","Ệ","Ể","Ễ",
						"Ì","Í","Ị","Ỉ","Ĩ",
						"Ò","Ó","Ọ","Ỏ","Õ","Ô","Ồ","Ố","Ộ","Ổ","Ỗ","Ơ","Ờ","Ớ","Ợ","Ở","Ỡ",
						"Ù","Ú","Ụ","Ủ","Ũ","Ư","Ừ","Ứ","Ự","Ử","Ữ",
						"Ỳ","Ý","Ỵ","Ỷ","Ỹ",
						"Đ"," ","/",":","*","?","<",">","|",'"');
			
				/*Mảng chứa tất cả ký tự không dấu tương ứng với mảng $marTViet bên trên*/
				$marKoDau=array("a","a","a","a","a","a","a","a","a","a","a",
						"a","a","a","a","a","a",
						"e","e","e","e","e","e","e","e","e","e","e",
						"i","i","i","i","i",
						"o","o","o","o","o","o","o","o","o","o","o","o",
						"o","o","o","o","o",
						"u","u","u","u","u","u","u","u","u","u","u",
						"y","y","y","y","y",
						"d",
						"A","A","A","A","A","A","A","A","A","A","A","A",
						"A","A","A","A","A",
						"E","E","E","E","E","E","E","E","E","E","E",
						"I","I","I","I","I",
						"O","O","O","O","O","O","O","O","O","O","O","O","O","O","O","O","O",
						"U","U","U","U","U","U","U","U","U","U","U",
						"Y","Y","Y","Y","Y",
						"D","-","","","","","","","","");
			
				if ($tolower) {
					return strtolower(str_replace($marTViet,$marKoDau,$cs));
				}
			
				return str_replace($marTViet,$marKoDau,$cs);
			
			}
			
			//minify JS AND CSS
			function minifyJS($arr){
				return $this->minify($arr, 'http://javascript-minifier.com/raw');
			}
			
			function minifyCSS($arr){
				return $this->minify($arr, 'http://cssminifier.com/raw');
			}
			
			function minify($arr, $url) {
				foreach ($arr as $key => $value) {
					$handler = fopen($value, 'w') or die("File <a href='" . $value . "'>" . $value . "</a> error!<br />");
					fwrite($handler, $this->getMinified($url, file_get_contents($key)));
					fclose($handler);
					//$this->flashMessenger()->addMessage(array('thanhcong' => 'minify file thành công'));
					//echo "File <a href='" . $value . "'>" . $value . "</a> done!<br />";
				}
				return 'minify file thành công';
			}
			
			function getMinified($url, $content) {
				$postdata = array('http' => array(
						'method'  => 'POST',
						'header'  => 'Content-type: application/x-www-form-urlencoded',
						'content' => http_build_query( array('input' => $content) ) ) );
				return file_get_contents($url, false, stream_context_create($postdata));
			}

		}
	?>	